<!-- src/components/ShowToast.vue -->
<template>
  <Teleport to="body">
    <transition name="fade">
      <div v-if="visible" class="toast" :class="`toast--${position}`">
        {{ message }}
      </div>
    </transition>
  </Teleport>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  message: {
    type: String,
    default: ''
  },
  position: {
    type: String,
    default: 'center',
    validator(value) {
      return ['top', 'center', 'bottom'].includes(value)
    }
  },
  duration: {
    type: Number,
    default: 2000
  }
})

const visible = ref(false)

// 显示后自动隐藏
watch(visible, (newVal) => {
  if (newVal) {
    const timer = setTimeout(() => {
      visible.value = false
    }, props.duration)
    // 可选：清理定时器（组件销毁时）
    // onScopeDispose(() => clearTimeout(timer))
  }
})

// 暴露方法给父组件调用
defineExpose({
  show() {
    visible.value = true
  },
  hide() {
    visible.value = false
  }
})
</script>

<style scoped>
.toast {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.75);
  color: white;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  z-index: 20000;
  max-width: 80%;
  text-align: center;
  word-break: break-word;
}

.toast--top {
  top: 20px;
}

.toast--center {
  top: 50%;
  transform: translate(-50%, -50%);
}

.toast--bottom {
  bottom: 50px;
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>